<template>
    <div>
        <el-dialog v-model="props.isShow" :title="props.isAdd ? '添加商品规格' : '编辑商品规格'" center :before-close="beforeClose">
            <el-form :model="specsForm" :rules="rules" ref="specsRef">

                <el-form-item label="规格名称" :label-width="formLabelWidth" prop="specsname">
                    <el-input v-model="specsForm.specsname" autocomplete="off" />
                </el-form-item>
                <!-- 动态添加 -->
                <el-form-item label="规格属性" v-for=" (item, index) in Attrs" :key="item" :label-width="formLabelWidth">
                    <el-input class="ipt" v-model="item.value" autocomplete="off" />
                    <el-button type="primary" @click="addAttrs" v-if="index == 0">添加规格属性</el-button>
                    <el-button plain v-else>删除</el-button>
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="specsForm.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" :active-value="1"
                        :inactive-value="2" />
                </el-form-item>

            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel(specsRef)">取消</el-button>
                    <el-button type="primary" @click="confirm(specsRef)">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang='ts' setup>
import { defineProps, defineEmits, defineExpose } from 'vue';
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue';
import { specsadd, specsedit, specsinfo } from '../../request/api';
import { useStore } from 'vuex';

let store = useStore();

let specsRef = ref();
// 接收父组件的参数
let props = defineProps({
    isShow: Boolean,
    isAdd: Boolean
})

let specsForm = ref({
    specsname: '',//商品规格名称string’颜色‘
    attrs: '',//商品规格属性值string"白色,红色，黄色"
    status: 1,//状态1正常2禁用number1
})

const rules = reactive<FormRules>({
    specsname: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' },
        { min: 2, max: 6, message: '请输入2-6为字符', trigger: 'blur' },
    ]
})
const formLabelWidth = '120px';

// 定义规格属性的数据
let Attrs = ref([
    {
        value: '',
    }
]);
// 添加规格属性
const addAttrs = () => {
    //   点击添加按钮  追加一个dom节点
    // 如果前一个没有值就不能追加
    if (!Attrs.value[0].value) {
        ElMessage.success('请填写属性');
        return;
    }
    
    Attrs.value.push({
        value: ''
    })

}
// 点击x号 关闭弹窗
const beforeClose = (done: any) => {
    done();
    cancel(specsRef.value);
}

// 调用子父传值方法
let emit = defineEmits(['cancel']);

// 取消
const cancel = (formEl: FormInstance | undefined) => {
    // 通知父组件
    emit('cancel');
    if (!formEl) return;
    // 清空表单
    specsForm.value = {
        specsname: '',//商品规格名称string’颜色‘
        attrs: '',//商品规格属性值string"白色,红色，黄色"
        status: 1,//状态1正常2禁用number1
    }
    // 重置属性
    Attrs.value = [{
        value: ''
    }]
    // 清空规则
    formEl.resetFields();
}
let newId = 0;//id初始值

// 回显
const lookup = (id: number) => {
    console.log(id, '回显');
    specsinfo({ id }).then((res: any) => {
        if (res.code == 200) {
            specsForm.value = res.list[0];
            newId = id
            // 处理属性
            res.list[0].attrs.map((item: any, index: number) => {
                //  如果下标是0的就直接赋值  否则就是追加
                if (index == 0) {
                    Attrs.value[0].value = item;
                } else {
                    Attrs.value.push({
                        value: item
                    })
                }

            })
        }
    })
}

// 确定
const confirm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate(val => {
        if (val) {
            // 处理数据格式
            let str = Attrs.value.map((item: any) => {
                return item.value
            });
            specsForm.value.attrs = str.join(',');
            // console.log(specsForm.value);

            if (props.isAdd) {
                // 添加
                specsadd(specsForm.value).then(res => {
                    if (res.code == 200) {
                        // 添加成功
                        ElMessage.success(res.msg);
                        // 关闭弹窗
                        cancel(specsRef.value);
                        // 重新渲染视图
                        store.dispatch('specs/getSpecsListActions');
                        // 重新获取总条数
                        store.dispatch('specs/getCountActions');
                    } else {
                        // 添加失败
                        ElMessage.error(res.msg)
                    }
                })

            } else {
                // 编辑
                specsedit({ ...specsForm.value, id: newId }).then(res => {
                    if (res.code == 200) {
                        // 编辑成功
                        ElMessage.success(res.msg);
                        // 关闭弹窗
                        cancel(specsRef.value);
                        // 重新渲染视图
                        store.dispatch('specs/getSpecsListActions')
                    }
                })
            }
        }
    })


}
defineExpose({
    lookup
})

</script>
<style scoped lang='less'>
.ipt {
    width: 70%;
    margin-right: 10px;
}
</style>